package cn.com.baiwei.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


/**
 * @description 上传图片
 * @author X_Q
 * @creat 2021-09-18 13:11
 **/
@Service
public class FileUpLoadServiceImpl {
    /**
     * 图片上传
     * @param file   文件
     * @return
     * @throws IOException
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public Map<String, Object> fileUpLoad(MultipartFile file, HttpServletRequest request) throws IOException, SQLException, ClassNotFoundException {
        HashMap<String, Object> map = new HashMap<>();
        String dirStr = "uploadPicture";
        String timeMillis = "" + System.currentTimeMillis();
        String filePath =request.getServletContext().getRealPath("")  +  dirStr  + File.separator  + timeMillis + file.getOriginalFilename();// 获取上传的文件名
        System.out.println("图片地址:"+filePath);
        File newFile = new File(filePath);
        FileCopyUtils.copy(file.getBytes(), newFile);
        String picturePath = File.separator +  File.separator + dirStr + File.separator + File.separator +timeMillis + file.getOriginalFilename() ;  // 组装一个浏览器识别的文件地址
        System.out.println("header=" + picturePath);
        map.put("code", 200);
        map.put("msg", "上传图片成功!");
        map.put("data", picturePath);
        return map;
    }
}
